//{{.Auth}}
package filter

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/plugins/cors"
	"github.com/astaxie/beego/context"
	"strings"
	"{{.ProjectUri}}/common"
	"encoding/json"
	"net/http"
	"{{.ProjectUri}}/msg"
)

func Cfg() {
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))

	beego.InsertFilter("*", beego.AfterExec, func(context *context.Context) {
		beego.Debug("url", context.Input.URL())
	})

	beego.InsertFilter("*", beego.BeforeExec, func(context *context.Context) {
		beego.Info("#", context.Input.Header("messageid"), "#", context.Input.URL())
	})

	beego.InsertFilter("/*", beego.BeforeRouter, func(ctx *context.Context) {

		beego.Info("ctx.Request.RequestURI", ctx.Request.RequestURI)
		var token = ""
		ctx.Request.ParseForm()

		if strings.ToUpper(ctx.Request.Method) == "GET" {
			if len(ctx.Request.Form["token"]) > 0 {
				token = ctx.Request.Form["token"][0]
			}
		} else if strings.ToUpper(ctx.Request.Method) == "POST" {
			token = ctx.Request.PostFormValue("token")
		}

		beego.Debug("token", token)

		if ctx.Request.RequestURI != "/api/readlogin" {
			//ctx.Redirect(302, "/login")
			if token != "" {
				//beego.Debug("token", token)
				//check token
				//v, ok := ctx.Input.Session("token").(string)

				entry, err := common.Cache.Get(token)

				if err != nil {

					if bytes, e := json.Marshal(msg.ResponseBuilder().NoTokenResponse().Build()); e == nil {
						ctx.ResponseWriter.Write(bytes)
					} else {
						ctx.ResponseWriter.WriteHeader(http.StatusInternalServerError)
					}

				} else {
					if entry != nil {
						beego.Debug(token, "token in cache", string(entry))
					} else {
						beego.Debug(token, "token not in cache")
						if bytes, e := json.Marshal(msg.ResponseBuilder().NoTokenResponse().Build()); e == nil {
							ctx.ResponseWriter.Write(bytes)
						} else {
							ctx.ResponseWriter.WriteHeader(http.StatusInternalServerError)
						}
					}
				}
			} else {
				if bytes, e := json.Marshal(msg.ResponseBuilder().NoTokenResponse().Build()); e == nil {
					ctx.ResponseWriter.Write(bytes)
				} else {
					ctx.ResponseWriter.WriteHeader(http.StatusInternalServerError)
				}
			}

		}

	})
}




